package cn.web.tunnelrobot.util;

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

/**
 *
 * @author LiGuoXian
 * @version 1.0.0
 *
 */
public class SendCode {
	public static String verQQEmailCode = "";// 邮箱验证码
	/**
	 * 生成4位验证码
	 */
	public static String getCheckCode() {
		// qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGJKLZXCVBNM
		String ZiMu = "1234567890";
		String result = "";
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			int index = random.nextInt(ZiMu.length());
			char c = ZiMu.charAt(index);
			result += c;
		}
		return result;
	}
	/**
	 * 发送验证码
	 *
	 * @param tos
	 */
	public static int sendEmailCode(String tos) {
		verQQEmailCode = getCheckCode();// 获取验证码
		// 创建Properties 类
		final Properties props = new Properties();
		// SMTP发送邮件
		props.put("mail.smtp.auth", "true");
		// 此处填写SMTP服务器
		props.put("mail.smtp.host", "smtp.163.com");
		// 端口号
		props.put("mail.smtp.port", "25");
		// 账号
		props.put("mail.user", "Mr_LGX@163.com");
		// 此处的密码就是前面说的16位STMP口令
		props.put("mail.password", "woaijava1314");
		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = props.getProperty("mail.user");
				String password = props.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		try {
			// 使用环境属性和授权信息，创建邮件会话
			Session mailSession = Session.getInstance(props, authenticator);
			// 创建邮件消息
			MimeMessage message = new MimeMessage(mailSession);
			// 设置发件人
			InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
			message.setFrom(form);
			// 设置收件人的邮箱
			InternetAddress to = new InternetAddress(tos);
			message.setRecipient(RecipientType.TO, to);
			message.setRecipient(RecipientType.CC, form);
			// 设置邮件标题
			message.setSubject("验证码");
			// 设置邮件的内容体
			message.setContent("【甘肃省高校大学生就业创业能力提升项目绩效评估系统】您的验证码是:" + verQQEmailCode,
					"text/html;charset=UTF-8");
			Transport.send(message);

			return 1;
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int i = sendEmailCode("1228181394@qq.com");
		System.out.println("i========="+i);
	}
}